package org.bbx.autoops.utils;

import cn.hutool.core.date.DateUtil;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.ces.v1.region.CesRegion;
import com.huaweicloud.sdk.ces.v1.*;
import com.huaweicloud.sdk.ces.v1.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.bbx.autoops.utils.ParamPackage.xyChart;


/**
 * 监控数据处理
 */
@Slf4j
@Component
public class CesUtil {


    @Value("${metric.config.region}")
    private String region;


    @Value("${metric.config.filter}")
    private String filter;

    @Value("${metric.config.period}")
    private Integer period;

    @Value("${hw.ak}")
    private String ak;

    @Value("${hw.sk}")
    private String sk;


    /**
     * 查询监控资源的监控数据
     *
     * @param namespace
     * @param metricName
     * @param dim0
     * @return
     */
    public ShowMetricDataResponse getMetricDate(String namespace, String metricName, String dim0, Long from, Long to) {
        ShowMetricDataResponse response = null;
        ICredential auth = new BasicCredentials().withAk(ak).withSk(sk);
        CesClient client = CesClient.newBuilder()
                .withCredential(auth)
                .withRegion(CesRegion.valueOf(region))
                .build();
        ShowMetricDataRequest request = new ShowMetricDataRequest()
                .withNamespace(namespace)
                .withMetricName(metricName)
                .withDim0(dim0)
                .withFilter(ShowMetricDataRequest.FilterEnum.fromValue(filter))
                .withPeriod(period)
                .withFrom(from)
                .withTo(to);
        try {
            response = client.showMetricData(request);


        } catch (RequestTimeoutException | ConnectionException e) {
            log.error(e.getMessage());
        } catch (ServiceResponseException e) {
            log.error(e.getMessage());
            log.error(String.valueOf(e.getHttpStatusCode()));
            log.error(e.getRequestId());
            log.error(e.getErrorCode());
            log.error(e.getErrorMsg());
        }
        return response;
    }


    /**
     * 获取监控数据，并且封装成 xy-chart 模板需要的数据格式
     *
     * @param namespace 资源的名称空间
     * @param dim0
     * @return
     */
    public Map<String, String> getXYChartDataMap(String id, String namespace, String metricName, String dim0, Long from, Long to) {
        ShowMetricDataResponse metricDate = getMetricDate(namespace, metricName, dim0, from, to);
        Map<String, String> m = new HashMap<>();
        if (metricDate == null) {
            return m;
        }
        StringBuilder valueBuilder = new StringBuilder();
        StringBuilder keyBuilder = new StringBuilder();
        List<Datapoint> datapoints = metricDate.getDatapoints();
        Double maXYChaxis = 0.0;
        if (!datapoints.isEmpty()) {
            String unit = datapoints.get(0).getUnit();

            for (int i = 0; i < datapoints.size(); i++) {
                Datapoint point = datapoints.get(i);
                Double v = 0.0;
                switch (filter) {
                    case "average":
                        v = point.getAverage();
                        break;
                    case "max":
                        v = point.getMax();
                        break;
                    case "min":
                        v = point.getMin();
                        break;
                    case "sum":
                        v = point.getSum();
                        break;
                    case "variance":
                        v = point.getVariance();
                        break;
                }

                if ("Byte".equals(unit)) {
                    unit = "MB";
                    v =  BigDecimal.valueOf(v).divide(BigDecimal.valueOf(1048576),2,RoundingMode.HALF_UP).doubleValue();
                }

                valueBuilder.append(v);

                keyBuilder.append('"').append(DateUtil.format(DateUtil.date(point.getTimestamp()), "MM/dd")).append('"');

                if (i < datapoints.size() - 1) {
                    valueBuilder.append(",");
                    keyBuilder.append(",");
                }


                // 处理最大值
                maXYChaxis = Math.max(maXYChaxis, v);
            }


            m = xyChart(maXYChaxis.toString(),
                    valueBuilder.toString(),
                    keyBuilder.toString(),
                    metricName,
                    unit,
                    id);
        }
        return m;
    }
}
